package com.dfrz.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.dfrz.common.ResultEnum;
import com.dfrz.config.CustomException;
import com.dfrz.entity.Result;
import com.dfrz.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 29877 定义拦截器
 */

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //目标资源执行之前执行  true:放行  false :拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径
        String url = request.getRequestURI().toString();
        //2.判断路径
        if(url.contains("login")){
            //账号密码登录，放行
            return true;
        }
        if(url.contains("pay")){
            return true;
        }

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }

        //3.获取请求头token,返回携带的令牌
        String jwt = request.getHeader("token");
        if(jwt == null){
            //返回登录页
            Result<Object> notLogin = Result.error(ResultEnum.NO_LOGIN.getCode(),ResultEnum.NO_LOGIN.getMsg());
            String data = JSONObject.toJSONString(notLogin);
            response.getWriter().write(data);
            return false;
        }
        //4.解析令牌
        try {
            JwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            //令牌存在问题
            throw new CustomException(ResultEnum.TOKEN_EX.getCode(),ResultEnum.TOKEN_EX.getMsg());
        }
        //令牌没有问题，放行
        return true;
    }
}
